using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using CommunityToolkit.Mvvm.Messaging;
using DialogHostAvalonia;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using SchoolApp_Material.Msgs;
using SchoolApp_Material.ViewModels;

namespace SchoolApp_Material.Views;

public partial class LoginWindow : Window
{
    public LoginWindow()
    {
        InitializeComponent();
        DataContext = Program.ServiceProvider.GetRequiredService<LoginViewModel>();
    }

    private void LoginWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        txtCode.Focus();
        WeakReferenceMessenger.Default.Register<LoginMsg>(this, (r, msg) =>
        {
            Console.WriteLine($"用户已登录: {msg.OperatorCode}");
            // 创建主窗口
            var mainWindow = new MainWindow();
            // 设置Program的MainWindow引用
            Program.MainWindow = mainWindow;
            // 显示主窗口
            mainWindow.Show();
            // 关闭登录窗口
            this.Close();
        });
        WeakReferenceMessenger.Default.Register<ErrorMsg>(this, async (r, msg) =>
        {
            var result = await DialogHost.Show(
                new MsgBoxView
                {
                    DataContext = new MsgBoxViewModel()
                    {
                        MsgBoxIcon = MsgBoxIcons.Error, 
                        Title = "错误", 
                        Content = msg.Data,
                        MsgBoxShowButton = MsgBoxShowButtons.Ok,
                        DefaultEscape = MsgBoxButtons.Ok,
                        DefaultEnter = MsgBoxButtons.Ok
                    }
                },
                "LoginWindowHost");
            if (result is MsgBoxButtons msgBoxButton)
            {

            }
        });
    }

    private void LoginWindow_OnUnloaded(object sender, RoutedEventArgs e)
    {
        WeakReferenceMessenger.Default.Unregister<LoginMsg>(this);
        WeakReferenceMessenger.Default.Unregister<ErrorMsg>(this);
    }

    private void txtCode_OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter)
            return;
        txtPwd.Focus();
    }

    private void txtPwd_OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;
        if (btnLogin.Command != null && btnLogin.Command.CanExecute(null))
            btnLogin.Command.Execute(null);
    }
}